package com.restaurant.springboot.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class DishesImageFileUitl {

    private static List<String> imageSuffixName;

    private static String filePath = System.getProperty("user.dir")+"\\src\\main\\resources\\static\\dishesImage\\";

    static {
        imageSuffixName = new ArrayList<>();
        imageSuffixName.add(".jpg");
        imageSuffixName.add(".pgn");
        imageSuffixName.add(".jpeg");
    }

    public static RespEntity uploadImage(int dishesId,MultipartFile file){
        if (file.isEmpty()) {
            return new RespEntity(RespCode.ERROR,"file is empty",null);
        }
        if(!checkFileSize(file.getSize(),10,"M")){
            return new RespEntity(RespCode.ERROR,"File is so big",null);
        }
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        if(!imageSuffixName.contains(suffixName)){
            return new RespEntity(RespCode.ERROR,"File format error",null);
        }
//        fileName = UUID.randomUUID() + suffixName; // 新文件名
        fileName = dishesId + suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        System.out.println(filePath);
        dest.getParentFile().mkdirs();
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new RespEntity(RespCode.SUCCESS,"upload success",null);
    }

    //判断文件大小
    public static boolean checkFileSize(Long len, int size, String unit) {
//        long len = file.length();
        double fileSize = 0;
        if ("B".equals(unit.toUpperCase())) {
            fileSize = (double) len;
        } else if ("K".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1024;
        } else if ("M".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1048576;
        } else if ("G".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1073741824;
        }
        if (fileSize > size) {
            return false;
        }
        return true;
    }

}
